#!/usr/bin/env python
# coding: utf-8
import web
from config import settings
from config.settings import session
from datetime import datetime
import sys,os,shutil
import ConfigParser
import base64
import hashlib
import authbase

db = settings.db
render_login = web.template.render('templates/')
render = settings.render
tb="alarms"
class Index:
    def GET(self):
        require_login()
        alarms = db.select(tb)
        return render.sysinfo.index(alarms=alarms)


def get_by_id(id):
    try:
        return db.select("users", where = 'id=$id', vars = locals())[0]
    except IndexError:
        return None

class ChangePassword(authbase.AuthBase):
    def GET(self):
        user = get_by_id(session.login_user_id)
        if not user:
            return render.error(u'没找到这条记录', None)
        return render.sysinfo.change_password(new_user=user)

    def POST(self):  
        i = web.input()
        password = i.get('password', None)
        if not password:
            return render.error(u'新密码不能为空', None)
        old_password = i.get('old_password', None)
        if not old_password:
            return render.error(u'原密码不能为空', None)

        id=session.login_user_id
        md5_old_password=hashlib.md5(old_password).hexdigest()
        user_result=db.query("select count(*) as count from users where id=%d and password='%s' "%(id,md5_old_password))[0]
        if user_result.count==0:
            return render.error(u'原密码不正确', None)

        md5_password=hashlib.md5(password).hexdigest()
        db.update("users", password=md5_password, where='id=$id', vars=locals())

        raise web.seeother('/')

###判断用户是否登陆  
def logged():  
    if session.get('login')==1:  
        return True  
    else:  
        return False

def require_login():
    if logged()==False:
        raise web.seeother("/login")

